package com.example.myblog.controller;

import com.example.myblog.model.Category;
import com.example.myblog.model.User;
import com.example.myblog.service.CategoryService;
import com.example.myblog.service.PostService;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 用户和管理面板相关的控制器
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PostService postService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 向所有模型中添加分类列表
    @ModelAttribute("categories")
    public List<Category> getCategories() {
        return categoryService.getAllCategories();
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String showLoginForm() {
        return "login";
    }

    /**
     * 显示管理员面板
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public String showAdminPanel(Model model) {
        model.addAttribute("users", userService.getAllUsers());
        model.addAttribute("posts", postService.getAllPosts());
        // categories 会通过 @ModelAttribute 自动添加
        return "admin/dashboard";
    }

    /**
     * 显示个人信息页面
     */
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/profile")
    public String showProfilePage(Model model) {
        String username = SecurityContextHolder.getContext()
                .getAuthentication().getName();
        User currentUser = userService.getUserByUsername(username);
        model.addAttribute("user", currentUser);
        // categories 会通过 @ModelAttribute 自动添加
        return "admin/profile";
    }

    /**
     * 处理个人信息更新请求
     */
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/admin/profile/update")
    public String updateProfile(
            @RequestParam("nickname") String nickname,
            @RequestParam("email") String email,
            @RequestParam(value = "newPassword", required = false) String newPassword,
            @RequestParam(value = "confirmPassword", required = false) String confirmPassword,
            @RequestParam("currentPassword") String currentPassword,
            @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile,
            RedirectAttributes redirectAttributes) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User currentUser = userService.getUserByUsername(auth.getName());

        if (!passwordEncoder.matches(currentPassword, currentUser.getPassword())) {
            redirectAttributes.addFlashAttribute("error", "当前密码不正确");
            return "redirect:/admin/profile";
        }

        currentUser.setNickname(nickname);
        currentUser.setEmail(email);

        if (newPassword != null && !newPassword.isEmpty()) {
            if (!newPassword.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的新密码不一致");
                return "redirect:/admin/profile";
            }
            currentUser.setPassword(passwordEncoder.encode(newPassword));
        }

        if (avatarFile != null && !avatarFile.isEmpty()) {
            // 注意：这里需要您的文件上传服务来处理头像
            // 例如: String avatarUrl = ossService.uploadFile(avatarFile);
            // currentUser.setAvatarUrl(avatarUrl);
            redirectAttributes.addFlashAttribute("message", "个人信息更新成功（头像上传功能待实现）");
        }

        userService.updateUser(currentUser.getId(), currentUser);
        redirectAttributes.addFlashAttribute("message", "个人信息更新成功");
        return "redirect:/admin/profile";
    }

    /**
     * 临时接口：创建默认管理员用户
     * 访问 /init-admin 来创建默认管理员
     */
    @GetMapping("/init-admin")
    public String initAdmin(RedirectAttributes redirectAttributes) {
        try {
            // 检查是否已经存在管理员用户
            if (userService.existsByUsername("admin")) {
                redirectAttributes.addFlashAttribute("message", "管理员用户已存在，用户名：admin");
                return "redirect:/login";
            }

            // 创建默认管理员用户
            User admin = new User();
            admin.setUsername("admin");
            admin.setPassword("admin123"); // 临时密码
            admin.setNickname("管理员");
            admin.setEmail("admin@example.com");
            
            userService.createUser(admin, true); // true表示创建管理员
            
            redirectAttributes.addFlashAttribute("message", "管理员用户创建成功！用户名：admin，密码：admin123");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "创建管理员用户失败：" + e.getMessage());
            return "redirect:/login";
        }
    }
}